(function() {
	
	var index = 1;
	var size = null;
	var imageIndexIdNum = 0;
	var starIndex = 0;
	var feedback = {
		question: document.getElementById('question'), 
		contact: document.getElementById('contact'), 
		imageList: document.getElementById('image-list'),
		submitBtn: document.getElementById('submit')
	};
	var url = 'http://app.xiaoweicanting.com/hospital.php?m=App&c=fault&a=addFault';
	var pics = [];//用于向index页面传递图片路径
	var picNum = 0;
	
	var checkPop1 = false;//用于判断故障原因及故障等级是否已经选择
	var checkPop2 = false;
	
	feedback.files = [];
	feedback.uploader = null;  
	feedback.deviceInfo = null; 
	mui.plusReady(function() {
		//设备信息，无需修改
		feedback.deviceInfo = {
			appid: plus.runtime.appid, 
			imei: plus.device.imei, //设备标识
			images: feedback.files, //图片文件
			p: mui.os.android ? 'a' : 'i', //平台类型，i表示iOS平台，a表示Android平台。
			md: plus.device.model, //设备型号
			app_version: plus.runtime.version,
			plus_version: plus.runtime.innerVersion, //基座版本号
			os:  mui.os.version,
			net: ''+plus.networkinfo.getCurrentType()
		}
	});
	
	

			(function($, doc) {
				
					var ui = {
						muimune1: doc.querySelector('.mui-mune1'),
						muimune2: doc.querySelector('.mui-mune2'),
						footerLeft: doc.querySelector('.footer-left'),
						btnMsgImage: doc.querySelector('#msg-image'),
						h: doc.querySelector('#h'),
						content: doc.querySelector('.mui-content')
					};
					
					var btnArray1 = new Array();
					mui.get('http://app.xiaoweicanting.com/hospital.php?m=App&c=fault&a=getFaultLevelList&uid=3&token=dfaf&specid=11',function(data){
						for(var i=0;i<data.data.length;i++){
						btnArray1[i]={title:data.data[i].name};
						}
					},'json')

					ui.muimune1.addEventListener('tap', function(event) {
						plus.nativeUI.actionSheet({
							cancel: "取消",
							buttons: btnArray1
						}, function(e) {
							var index = e.index;
//							if(index == 0) break;
							if(index != 0) {
								checkPop1 = true;						
								document.getElementById("breakReason").innerHTML = btnArray1[index-1].title;
							}
						});
					}, false);
					
					var btnArray2 = new Array();
					mui.get('http://app.xiaoweicanting.com/hospital.php?m=App&c=fault&a=getFaultLevelList&uid=3&token=dfaf&specid=11',function(data){
						for(var i=0;i<data.data.length;i++){
						btnArray2[i]={title:data.data[i].name};
						}
					},'json')

					ui.muimune2.addEventListener('tap', function(event) {
						plus.nativeUI.actionSheet({
							cancel: "取消",
							buttons: btnArray2
						}, function(e) {
							var index = e.index;
//							if(index == 0) break;
							if(index != 0) {
								checkPop2 = true;
								console.log("pop2"+checkPop2)
								document.getElementById("breakPicker").innerHTML = btnArray2[index-1].title;
							}
						});
					}, false); 
			}(mui, document));
	
	/**
	 *提交成功之后，恢复表单项 
	 */
	feedback.clearForm = function() {
		feedback.question.value = '';
		feedback.contact.value = '';
		feedback.imageList.innerHTML = '';
		feedback.newPlaceholder();
		feedback.files = [];
		index = 0;
		size = 0;
		imageIndexIdNum = 0;
		starIndex = 0;
		//清除所有星标
		mui('.icons i').each(function (index,element) {
			if (element.classList.contains('mui-icon-star-filled')) {
				element.classList.add('mui-icon-star')
	  			element.classList.remove('mui-icon-star-filled')
			}
		})
	};
	feedback.getFileInputArray = function() {
		return [].slice.call(feedback.imageList.querySelectorAll('.file'));
	};
	feedback.addFile = function(path) {
		feedback.files.push({name:"images"+index,path:path,id:"img-"+index});
		index++;
	};
	/**
	 * 初始化图片域占位
	 */
	feedback.newPlaceholder = function() {
		var fileInputArray = feedback.getFileInputArray();
		if (fileInputArray &&
			fileInputArray.length > 0 &&
			fileInputArray[fileInputArray.length - 1].parentNode.classList.contains('space')) {
			return;
		};
		imageIndexIdNum++;
		var placeholder = document.createElement('div');
		placeholder.setAttribute('class', 'image-item space');
		var up = document.createElement("div");
		up.setAttribute('class','image-up')
		//删除图片
		var closeButton = document.createElement('div');
		closeButton.setAttribute('class', 'image-close');
		closeButton.innerHTML = 'X';
		closeButton.id = "img-"+index;
		//小X的点击事件
		closeButton.addEventListener('tap', function(event) {
			setTimeout(function() {
				for(var temp=0;temp<feedback.files.length;temp++){
					if(feedback.files[temp].id==closeButton.id){
						feedback.files.splice(temp,1);
					}
				}
				feedback.imageList.removeChild(placeholder);
			}, 0);
			return false;
		}, false);
		
		//
		var fileInput = document.createElement('div');
		fileInput.setAttribute('class', 'file');
		fileInput.setAttribute('id', 'image-' + imageIndexIdNum);
		fileInput.addEventListener('tap', function(event) {
			var self = this;
			var index = (this.id).substr(-1);
						
						var btnArray = [{
							title: "拍照"
						}, {
							title: "从相册选择"
						}];
						plus.nativeUI.actionSheet({
							title: "选择照片",
							cancel: "取消",
							buttons: btnArray
						}, function(e) {
							var index = e.index;
							switch (index) {
								case 0:
									break;
								case 1:
									var cmr = plus.camera.getCamera();
									cmr.captureImage(function(e) {
				console.log("event:"+e);
				var name = e.substr(e.lastIndexOf('/') + 1);
				console.log("e:"+e);
				console.log("name:"+name);
				
					
				plus.zip.compressImage({
					src: e,
					dst: '_doc/' + name,
					overwrite: true,
					quality: 50
				}, function(zip) {
					size += zip.size  
					console.log("filesize:"+zip.size+",totalsize:"+size);
					if (size > (10*1024*1024)) {
						return mui.toast('文件超大,请重新选择~');
					}
					if (!self.parentNode.classList.contains('space')) { //已有图片
						feedback.files.splice(index-1,1,{name:"images"+index,path:e});
					} else { //加号
						placeholder.classList.remove('space');
						feedback.addFile(zip.target);
						
						feedback.newPlaceholder();
					}
					console.log("zip.target"+zip.target);
					pics[picNum] = zip.target;//在pics[]中添加图片路径。
					picNum++;
					up.classList.remove('image-up');
					placeholder.style.backgroundImage = 'url(' + zip.target + ')';
				}, function(zipe) {
					mui.toast('压缩失败！')
				});
			}, function(err) {});
			break;
									
			case 2:
				plus.gallery.pick(function(e) {
//				console.log("event:"+e);
				console.log("e:"+e);
				var name = e.substr(e.lastIndexOf('/') + 1);
				console.log("name:"+name);
				pics[picNum] = e;//在pics[]中添加图片路径。
				picNum++;
					
				plus.zip.compressImage({
					src: e,
					dst: '_doc/' + name,
					overwrite: true,
					quality: 50
				}, function(zip) {
					size += zip.size  
					console.log("filesize:"+zip.size+",totalsize:"+size);
					if (size > (10*1024*1024)) {
						return mui.toast('文件超大,请重新选择~');
					}
					if (!self.parentNode.classList.contains('space')) { //已有图片
						feedback.files.splice(index-1,1,{name:"images"+index,path:e});
					} else { //加号
						placeholder.classList.remove('space');
						feedback.addFile(zip.target);
						feedback.newPlaceholder();
					}
					up.classList.remove('image-up');
					placeholder.style.backgroundImage = 'url(' + zip.target + ')';
				}, function(zipe) {
					mui.toast('压缩失败！')
				});
			}, function(err) {}, null);
					break;
				 			}
						});
					}, false); 
		
		/****/
		placeholder.appendChild(closeButton);
		placeholder.appendChild(up);
		placeholder.appendChild(fileInput);
		feedback.imageList.appendChild(placeholder);
	};
	feedback.newPlaceholder();
	feedback.submitBtn.addEventListener('tap', function(event) {
		/*
		if (feedback.question.value == '' ||
			(feedback.contact.value != '' &&
				feedback.contact.value.search(/^(\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+)|([1-9]\d{4,9})$/) != 0)) {
			check = false;
			return mui.toast('手机信息填写不符合规范');
		}*/
		
		//判断网络连接
		var checkTele = /^[1][34587]\d{9}$/;
		var checkPhone = /^0\d{2,3}-?\d{7,8}$/;
				var check = true;
				textarea = document.getElementById("question").value;
				
				mui("textarea").each(function() {
				//若当前input为空，则alert提醒 
				if(!this.value || this.value.trim() == "") {
				    mui.toast("故障描述及联系方式不允许为空");
				    check = false;
				    return false;
				}
				if (!checkPhone.test(feedback.contact.value) && !checkTele.test(feedback.contact.value)) {//验证手机号，以1开头，十一位
						console.log("contact"+feedback.contact.value);
					check = false;
					return mui.toast('请输入正确的手机号或座机号，座机请加区号');
				}
				if (this.value.length > 200 || contact.value.length > 20) {
					check = false;
					mui.toast('信息超长,请重新填写~');
					return false;
				}
				if(plus.networkinfo.getCurrentType()==plus.networkinfo.CONNECTION_NONE){
					check = false;
					mui.toast("连接网络失败，请稍后再试");
					return false;
				}
			}); 
			if(!checkPop1){
				check = false;
				mui.toast("请选择故障原因");
				return false;
			}
			if(!(checkPop2)){
				check = false;
				mui.toast("请选择故障等级");
				return false;
			}
				//校验通过，继续执行业务逻辑
				if(check){
					mui.openWindow({
						url: 'addFault2.html', 
						id:'submit',
						extras:{//向下个页面传输的值
							Title:document.getElementById("breakReason").innerHTML,
							Question:document.getElementById("question").value,
							Contact:document.getElementById("contact").value,
							Faultlever:document.getElementById("breakPicker").innerHTML,
							Faultpics:feedback.files,
							PicsRoad:pics,
						},
						styles:{
							scrollIndicator:'none'
						}
					});
				}
	}, false)
	
	
})();
